﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spring.Data.NHibernate;
using NHibernate.Cfg;
using System.IO;
using System.Reflection;
using NHibernate.Mapping.Attributes;
using NHibernate.Mapping.ByCode;

namespace Dao.UQBuy
{
    public class MyLocalSessionFactoryObject : LocalSessionFactoryObject
    {
        /// <summary>
        /// 实体类所在的程序集的名称
        /// </summary>
        public string[] ModelAssemblyName { get; set; }
        /// <summary>
        /// NHibernate.Mapping.Attributes  此种方式映射源代码,需要引用NHibernate.Mapping.Attributes.dll
        /// </summary>
        /// <param name="config"></param>
        protected override void PostProcessConfiguration(Configuration config)
        {
            //base.PostProcessConfiguration(config);
            //HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();//Profiler监控记录日志
            //MemoryStream stream = new MemoryStream();
            //HbmSerializer.Default.Validate = true;
            //foreach (string modelAssemblyName in ModelAssemblyName)
            //{
            //    Assembly assembly = Assembly.Load(modelAssemblyName);
            //    HbmSerializer.Default.Serialize(stream, assembly);
            //    stream.Position = 0;
            //    Console.WriteLine(stream);
            //    config.AddInputStream(stream);
            //}

            base.PostProcessConfiguration(config);
            HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();//Profiler监控记录日志
            ModelMapper mappers = new ModelMapper();
            foreach (string modelAssemblyName in ModelAssemblyName)
            {
                Assembly assembly = Assembly.Load(modelAssemblyName);
                mappers.AddMappings(assembly.GetExportedTypes());
                var hbmMapping = mappers.CompileMappingForAllExplicitlyAddedEntities();
                // Console.WriteLine(hbmMapping.AsString());
                config.AddDeserializedMapping(hbmMapping, "");
            }
        }

    }
}
